<?php
//在任何HTML输出之前开启会话
session_start();
$username = trim($_POST['username']); //使用POST全局数组获取前端表单提交的数据
$pw = trim($_POST['pw']);
//进行必要的数据验证
if(!strlen($username) || !strlen($pw)){
    echo "<script>alert('用户名和密码都必须要填写');history.back();</script>";
    exit;
}
else{
    if(!preg_match('/^[a-zA-Z0-9]{3,10}$/',$username)){
        echo "<script>alert('用户名只能是大小字字符和数字构成，长度为3-10个字符');history.back();</script>";
        exit;
    }
    if(!preg_match('/^[a-zA-Z0-9_*]{6,10}$/',$pw)){
        echo "<script>alert('密码只能是大小字字符和数字，以及*、_构成，长度为6-10个字符');history.back();</script>";
        exit;
    }
}
include_once "conn.php";
$pw = md5($pw);
$source = $_POST['source']; //如果其值为admin，则是管理员登录，否则是普通用户登录
$table = $source === 'admin' ? 'admin' : 'userinfo';
$sql = "select id from $table where username = '$username' and pw = '$pw'";
$result = mysqli_query($conn,$sql);
if(mysqli_num_rows($result)){
    $info = mysqli_fetch_array($result,MYSQLI_ASSOC);
    if($source === 'admin'){
        //说明是管理员登录
        $_SESSION['isAdmin'] = 1;
        $url = 'admin.php';
    }
    else{
        unset($_SESSION['isAdmin']);
        $url = 'index.php';
    }
    $_SESSION['loggedUserID'] = $info['id'];
    $_SESSION['loggedUsername'] = $username;//写入会话标志
    echo "<script>alert('登录成功');location.href='$url';</script>";
}
else{
    unset($_SESSION['loggedUsername'],$_SESSION['loggedUserID']);
    echo "<script>alert('登录失败');history.back();</script>";
}